# coding: utf-8


from flask import Flask, redirect, request, url_for
from flask import render_template, make_response, jsonify
from pathlib import Path
import os

from utils.baidu import Baidu
from utils.qq import QQ
from utils.weibo import Weibo


app = Flask(__name__)


@app.route('/')
def index():
    baidu_news = Baidu().get_tops(50)
    qq_news = QQ().get_tops(10)
    weibo_news = Weibo().get_tops(10)

    return render_template("index.html", **{
        "baidu_news": baidu_news,
        "qq_news": qq_news,
        "weibo_news": weibo_news,
    })


@app.route('/refresh/all')
def refresh_all():
    os.system("scrapy crawl weibo --logfile {}".format(log_file("weibo.log")))
    os.system("scrapy crawl qq --logfile {}".format(log_file("qq.log")))
    os.system("scrapy crawl baidu --logfile {}".format(log_file("baidu.log")))

    return redirect(url_for("index"))


@app.route('/refresh/baidu')
def refresh_baidu():
    os.system("scrapy crawl baidu --logfile {}".format(log_file("baidu.log")))
    return redirect(url_for("index"))


@app.route('/refresh/qq')
def refresh_qq():
    os.system("scrapy crawl qq --logfile {}".format(log_file("qq.log")))
    return redirect(url_for("index"))


@app.route('/refresh/weibo')
def refresh_weibo():
    os.system("scrapy crawl weibo --logfile {}".format(log_file("weibo.log")))
    return redirect(url_for("index"))


def refresh():
    #open("logs/baidu.log", "w").write("")
    #open("logs/qq.log", "w").write("")
    #open("logs/weibo.log", "w").write("")
    os.system("scrapy crawl weibo --logfile {}".format(log_file("weibo.log")))
    os.system("scrapy crawl qq --logfile {}".format(log_file("qq.log")))
    os.system("scrapy crawl baidu --logfile {}".format(log_file("baidu.log")))
    #os.system("scrapy crawl qq --logfile {}".format(log_file("qq.log")))
    #subprocess.check_call(["scrapy", "crawl", "baidu", "--logfile", log_file("baidu.log")])
    #subprocess.check_call(["scrapy", "crawl", "qq", "--logfile", log_file("qq.log")])

    return redirect(url_for("index"))


def render_json(data, code=201):
    response = make_response(jsonify(data), code)
    return response


def log_file(filename):
    log_dir = os.path.join(os.path.dirname(__file__), "logs")
    log_file = os.path.join(log_dir, filename)

    if not os.path.isdir(log_dir):
        os.makedirs(log_dir)

    if not os.path.isfile(log_file):
        Path(log_file).touch()

    return log_file


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9000)
